package com.medicine.cs;

import java.io.UnsupportedEncodingException;
import java.util.Random;
import java.util.Scanner;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.medicine.controller.CombatScoreController;

public class StartGame {

	public static Scanner scan = new Scanner(System.in);
	
	private static Logger logger = LoggerFactory.getLogger(StartGame.class);
	
	private static String www="http://ali.zhxgj.cn:8080/Medicine";
	
	private static String patternForString = "\\w{1,16}";
	
	private static String patternForInt = "\\d{1,3}";

	private static String id;

	public static void main(String[] args) throws UnsupportedEncodingException {
		boolean isInit = false;
		while (!isInit) {
			isInit = initShow();
		}
		//id = "1";
		combatscore_add(id);

		
		boolean isGame = true;
		logger.info("欢迎来到石头剪刀布，人机争霸战。游戏现在正式开始");
		while (isGame) {
			isGame = start(id);
		}

		logger.info("欢迎来到石头剪刀布，人机争霸战。游戏现在正式结束");

	}

	// 开始展示信息
	public static Boolean initShow() throws UnsupportedEncodingException {
		logger.info("欢迎来到石头剪刀布，人机争霸战");
		logger.info("请输入选项:1.登陆,2注册");
		String selectString = scan.nextLine();
		if(!check(patternForInt,selectString))
			return false;
		if ("1".equals(selectString)) {
			return login();
		} else if ("2".equals(selectString)) {
			return register() ? login() : false;
		} else {
			logger.info("输入错误,请重新输入");
			return initShow();
		}
	}

	// 登录
	public static Boolean login() {

		logger.info("欢迎来到石头剪刀布，人机争霸战。开始登陆");
		
		logger.info("请输入用户名");
		String username = scan.nextLine();
		if(!check(patternForString,username))
			return false;
		logger.info("请输入密码");
		String passwd = scan.nextLine();
		if(!check(patternForString,passwd))
			return false;
		logger.info("正在登陆，请稍候");
		String jsonString = HttpRequest.sendPost2(
				www+"/login.html",
				// "username=" + username + "&passwd=" + passwd);
				"{\"username\":\"_username\",\"userpwd\":\"_userpwd\"}"
						.replaceAll("_username", username).replaceAll(
								"_userpwd", passwd));
		logger.debug(username + "   " + passwd + "   " + jsonString);
		JSONObject jobj = JSON.parseObject(jsonString);
		if (jobj.getInteger("code") == 200
				&& jobj.getString("data")!=null) {
			logger.info(jobj.getString("msg"));
			id=jobj.getJSONObject("data").getString("userid");
			return true;
		} else {
			logger.info("登陆失败");
			return false;
		}
	}

	// 注册
	public static Boolean register() throws UnsupportedEncodingException {
		logger.info("欢迎来到石头剪刀布，人机争霸战。开始注册");
		logger.info("请输入用户名");
		String username = scan.nextLine();
		if(!check(patternForString,username))
			return false;
		logger.info("请输入密码");
		String passwd = scan.nextLine();
		if(!check(patternForString,passwd))
			return false;
		logger.info("正在注册，请稍候");
		String jsonString = HttpRequest.sendPost2(
				www+"/register.html",
				"{\"username\":\"_username\",\"userpwd\":\"_userpwd\"}"
						.replaceAll("_username", username).replaceAll(
								"_userpwd", passwd));
		jsonString=new String(jsonString.getBytes("utf-8"), "utf-8");
		logger.debug(username + "   " + passwd + "   " + jsonString);
		JSONObject jobj = JSON.parseObject(jsonString);
		if (jobj.getInteger("code") == 200
				&& jobj.getString("data")!=null) {
			logger.info(jobj.getString("msg"));
			return true;
		} else {
			logger.info("注册失败");
			return false;
		}
	}

	// 注册后初始化战绩
	public static void combatscore_add(String id) {

		String jsonString = HttpRequest.sendGet(
				www+"/api/game/combatscore/add", "id="+id);
		logger.debug(jsonString);
		JSONObject jsonobject = JSON.parseObject(jsonString);
		if (jsonobject.getInteger("code") == 0) {
			logger.info("初始化战绩"+jsonobject.getString("message"));
		} else {
			logger.info("初始化战绩时发现"+jsonobject.getString("message"));
		}
		
	}

	// 开始游戏
	public static boolean start(String id) {
		combatscoreAndOnlineCount_query(id);
		// 页面中统一规定，石头为0，剪刀为1，布为2
		logger.info("请出拳:石头为0，剪刀为1，布为2/或者输入99退出");
		String wj_num_String= scan.nextLine();
		if(!check(patternForInt,wj_num_String))
			return true;
		int wj_num=Integer.parseInt(wj_num_String);
		// 判断是否要退出
		if (wj_num == 99) {
			return false;
		}
		int round_num = random();

		if (wj_num == 0 && round_num == 0) {
			logger.info("您出石头,电脑出石头,平局");
			combatscore_update(id, 2);

		} else if (wj_num == 0 && round_num == 1) {
			logger.info("您出石头,电脑出剪刀,胜局");
			combatscore_update(id, 0);
			combatscoreAndOnlineCount_query(id);
		} else if (wj_num == 0 && round_num == 2) {
			logger.info("您出石头,电脑出布,敗局");
			combatscore_update(id, 1);
		} else if (wj_num == 1 && round_num == 0) {
			logger.info("您出剪刀,电脑出石头,敗局");
			combatscore_update(id, 1);
		} else if (wj_num == 1 && round_num == 1) {
			logger.info("您出剪刀,电脑出剪刀,平局");
			combatscore_update(id, 2);
		} else if (wj_num == 1 && round_num == 2) {
			logger.info("您出剪刀,电脑出布,胜局");

			combatscore_update(id, 0);
		} else if (wj_num == 2 && round_num == 0) {
			logger.info("您出布,电脑出石头,胜局");
			combatscore_update(id, 0);
		} else if (wj_num == 2 && round_num == 1) {
			logger.info("您出布,电脑出剪刀,敗局");
			combatscore_update(id, 1);
		} else if (wj_num == 2 && round_num == 2) {
			logger.info("您出布,电脑出布,平局");
			combatscore_update(id, 2);
		} else {
			logger.info("您输入的不在范围，请重新数据");
		}
		return true;
	}

	// 战绩更新
	public static Boolean combatscore_update(String id, int code) {

		String jsonString = HttpRequest
				.sendPost2(
						www+"/api/game/combatscore/update",
						"{\"id\":\"_id\",\"code\":\"_code\"}".replaceAll("_id",
								id).replaceAll("_code", code + ""));
		logger.debug("id:" + id + "   code:" + code + "   返回:" + jsonString);
		JSONObject jobj = JSON.parseObject(jsonString);
		if (jobj.getInteger("code") == 0) {
			logger.info("上局战绩已上传");
			return true;
		} else {
			logger.info("上局战绩上传失败");
			return false;
		}
		// 更新完后获取一边战绩
	}

	// 战绩和在线人数查询
	public static void combatscoreAndOnlineCount_query(String id) {

		// 获取在线人数
		String jsonStringForOnlineCount = HttpRequest.sendGet(
				www+"/loginOnline.html", "");
		logger.debug(jsonStringForOnlineCount);
		JSONObject jsonobjectForOnlineCount = JSON
				.parseObject(jsonStringForOnlineCount);
		if (jsonobjectForOnlineCount.getInteger("code") == 200) {
			logger.info("在线人数统计:" + jsonobjectForOnlineCount.getString("data"));
		} else {
			logger.info("查询在线人数失败!");
		}
		// 获取战绩
		String jsonStringForcombatscore = HttpRequest.sendGet(
				www+"/api/game/combatscore/query",
				"id="+id);
		logger.debug(id + "   " + jsonStringForcombatscore);
		JSONObject joForcombatscore = JSON
				.parseObject(jsonStringForcombatscore);
		if (joForcombatscore.getInteger("code") == 0) {
			logger.info("总局数："
					+ joForcombatscore.getJSONObject("data").getString("total"));
			logger.info("赢局数："
					+ joForcombatscore.getJSONObject("data").getString("win"));
		} else {
			logger.info("获取战绩失败");
		}
	}

	// 生成0-2之间的整数
	public static int random() {
		int max = 2;
		int min = 0;
		Random random = new Random();
		int s = random.nextInt(max) % (max - min + 1) + min;
		return s;
	}
	
	public static boolean check(String pattern,String content){
		boolean isMatch = Pattern.matches(pattern, content);
		if(!isMatch)
			logger.info("您输入的有误，请按要求输入（数字输入最多3位，字母最多16位）");
		return isMatch;
	}

}
